package com.spring.demo.core.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import com.spring.demo.core.entity.Order;
import com.spring.demo.core.entity.Order.Status;
import com.spring.demo.core.event.OnOrderDelivered;
import com.spring.demo.core.event.OnOrderPostponed;
import com.spring.demo.core.service.IOrderServer;

/**
 * 
 * @author sean
 * 
 */
@Service("orderServer")
public class OrderServer implements IOrderServer,
		ApplicationEventPublisherAware {

	private ApplicationEventPublisher eventPublisher;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void setApplicationEventPublisher(
			ApplicationEventPublisher applicationEventPublisher) {
		this.eventPublisher = applicationEventPublisher;
	}

	@Override
	public void delivered(Order order) {
		Status status = order.getStatus();
		if (status != Status.CHECKED_OUT && status != Status.POSTPONED) {
			throw new IllegalArgumentException(
					"Order status should be CHECKED_OUT or POSTPONED for delivered to called, but is "
							+ status);
		}
		order.setStatus(Status.DELIVERED);
		order.setUpdateDate(new Date());
		this.eventPublisher.publishEvent(new OnOrderDelivered(order));
	}

	@Override
	public void postponed(Order order) {
		order.setStatus(Status.POSTPONED);
		order.setUpdateDate(new Date());

		this.eventPublisher.publishEvent(new OnOrderPostponed(order));
		logger.debug("after POSTPONED email send: OrderServer postponed end!");
	}

}
